/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.admin.users.client;

import java.util.ArrayList;

import com.citep.web.admin.accounts.client.AccountEntryModule;
import com.citep.web.admin.accounts.client.AccountService;
import com.citep.web.admin.accounts.client.AccountServiceAsync;
import com.citep.web.admin.accounts.client.CategoryShortcut;
import com.citep.web.gwt.dto.*;
import com.citep.web.gwt.module.*;
import com.citep.web.gwt.widgets.DynaTableDataProvider;
import com.citep.web.gwt.widgets.DynaTableDataProvider.RowDataAcceptor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

public class UserListApplication implements DynaTableDataProvider {
	
	protected ArrayList currentList; //list with accounts being currently displayed
	
	protected void pushResults(int startRow, int maxRows, ArrayList userList, RowDataAcceptor acceptor) {
		
		int listSize = userList.size();
		String [][] rows = new String[listSize][];
		
		for(int i = 0; i < listSize; i++) {

			UserDTO user = (UserDTO)userList.get(i);
	
			rows[i] = new String[5];
			rows[i][0] = user.getFirstName();
			rows[i][1] = user.getLastName();
			rows[i][2] = user.getEmail();
			rows[i][3] = user.getRoleName();			
		}
		
		acceptor.accept(startRow, rows);
		
		currentList = userList;
	}
	
	public void updateRowData(final int startRow, final int maxRows, final RowDataAcceptor acceptor) {
		
		AsyncCallback userListCallBack = new AsyncCallback() {
			public void onSuccess(Object result) {
				ArrayList userList = (ArrayList)result;
				pushResults(startRow, maxRows, userList, acceptor);
			}
			
			public void onFailure(Throwable caught) {
				System.out.println(":" + caught.getMessage());
				caught.printStackTrace();
			}
		};

		accountsService.getUsers(startRow, maxRows, userListCallBack);
	}

	protected UserListPresentation presentation;

	protected AccountServiceAsync accountsService; 
	
	public UserListApplication() {
		accountsService = (AccountServiceAsync)GWT.create(AccountService.class);
		((ServiceDefTarget)accountsService).setServiceEntryPoint(GWT.getModuleBaseURL() + "/accounts");
	}
	
	public void setPresentation(UserListPresentation presentation) {
		this.presentation = presentation;
	}	

	protected void processException(Throwable caught) {
		
		String msg = caught.getMessage();

		if(msg.substring(0, 2).equals("__")) {
			
			/*
			 * We must make sure that we cover the case where the string ends in __
			 * or not, since GWT's javascript version of String.split() works different
			 * than java's String.split() for empty tokens.
			 */
			String [] tokens;
			if(msg.substring(msg.length()-2, msg.length()).equals("__"))
				tokens = msg.substring(2,msg.length()-2).split("__");
			else
				tokens = msg.substring(2,msg.length()).split("__");
			
			String type = tokens[0];
			
			if(type.equals("validation")) {
				
				//there most be an even number of tokens (key:value pairs)
				if((tokens.length - 1) % 2 == 0) {
					
					for(int i = 1; i < tokens.length; i += 2) {
						String key = tokens[i];
						String value = tokens[i+1];
						presentation.displayError(key,value);
					}
				}
			} else {
				presentation.displayStatus(caught.getMessage(), 10);
				System.out.println(":::" + caught.getMessage());
				caught.printStackTrace();
			}
		} else {
			presentation.displayStatus(caught.getMessage(), 10);			
			System.out.println(":::" + caught.getMessage());
			caught.printStackTrace();
		}
		
		
	}
	
	
	public void refreshUserList() {
		presentation.getDataGrid().refresh();
	}
	
	
	public void onRowClicked(int row) {
		if(currentList != null) {
			//make sure that the user didn't click on an empty row
			if(row < currentList.size()) {
				UserDTO user = (UserDTO)currentList.get(row);
				
				//tell the account edit module to retrieve this account
				//UserEntryModule.getInstance().getApplication().getUser(user.getId());
				//go to that screen
//				History.onHistoryChanged("edit_account");
				String token = HistoryEncoder.encode("edit_user",new Integer(user.getId()));
				History.newItem(token);
			}
		}
	}
}